package org.csu.domitory.controller;

import org.csu.domitory.domain.Account;
import org.csu.domitory.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/account/")
@SessionAttributes({"account"})
public class AccountController {

    @Autowired
    private AccountService accountService;
    //注册页面
    @GetMapping("newAccount")
    public String NewAccount() {

        return "common/newAccount";
    }

    //登录页面
    @GetMapping("login")
    public String login() {
        return "common/login";
    }

    //管理员登录页面
    @GetMapping("admin")
    public String adminLogin() {
        return "admin/login";
    }

    @GetMapping("adminMain")
    public String adminMain() {
        return "admin/main/main";
    }

    //主页面
    @PostMapping("main")
    public String main(String userId, String password, Model model)
    {
        Account account=accountService.getAccountByUsernameAndPassword(userId,password);
        model.addAttribute("account",account);
        return "common/main";
    }

    //登录验证
    @GetMapping("checkLogin")
    @ResponseBody
    public String checkLogin(String userId,String password){
        Account account=accountService.getAccountByUsernameAndPassword(userId,password);
        if (account==null){
            return "fail";
        }else {
            return "success";
        }
    }

    //验证用户名是否存在
    @GetMapping("checkUser")
    @ResponseBody
    public String checkUser(String userId){
        System.out.println(userId);
        Account account=accountService.getAccount(userId);
        if (account!=null){
            return "fail";
        }else{
            return "success";
        }
    }
    //注册成功
    @PostMapping("register")
    @ResponseBody
    public String register(String userId,String password){
        try {
            accountService.insertStud(userId, password);
            return "success";
        }catch (Exception e){
            return "fail";
        }
    }
}
